package client.cell;

import common.bodies.FriendShipBody;
import common.bodies.UserBody;
import javafx.scene.control.*;
import javafx.scene.input.MouseEvent;

public class FriendCell extends ListCell<FriendShipBody> {
    private final UserBody currentUser;

    //  回调接口
    private OnFriendActionListener listener;

    public FriendCell(UserBody user) {
        this.currentUser = user;

        // 添加点击事件监听
        this.addEventFilter(MouseEvent.MOUSE_CLICKED, e -> {
            if (!isEmpty() && getItem() != null && e.getClickCount() == 1 && listener != null) {
                listener.onClick(getItem());
            }
        });
    }

    @Override
    protected void updateItem(FriendShipBody item, boolean empty) {
        super.updateItem(item, empty);

        if (empty || item == null) {
            setText(null);
            setContextMenu(null);
        } else {
            String friendName = item.getUser1Name().equals(currentUser.getName())
                    ? item.getUser2Name()
                    : item.getUser1Name();

            setText(friendName);
            setStyle("-fx-font-size: 14px; -fx-padding: 5px;");


            ContextMenu contextMenu = new ContextMenu();

            MenuItem deleteItem = new MenuItem("🗑 删除好友");
            deleteItem.setOnAction(e -> {
                if (listener != null) listener.onDelete(item);
            });

            MenuItem blockItem = new MenuItem("🚫 拉黑好友");
            blockItem.setOnAction(e -> {
                if (listener != null) listener.onBlock(item);
            });
//
//            MenuItem clearItem = new MenuItem("💬 清空聊天记录");
//            clearItem.setOnAction(e -> {
//                if (listener != null) listener.onClearHistory(item);
//            });

            contextMenu.getItems().addAll(deleteItem, blockItem);
            setContextMenu(contextMenu);
        }
    }

    //  设置回调接口
    public void setOnFriendActionListener(OnFriendActionListener listener) {
        this.listener = listener;
    }

    //  回调接口定义
    public interface OnFriendActionListener {
        void onClick(FriendShipBody friend);
        void onDelete(FriendShipBody friend);
        void onBlock(FriendShipBody friend);
//        void onClearHistory(FriendShipBody friend);
    }
}
